import React from 'react';
import Chart from 'chart.js/src/chart';
import {colors, ajaxUtil} from '../utils';
import Paper from 'material-ui/Paper';
import $ from 'jquery';
import {myStyles} from '../utils';

export default class Statistic extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '',
            questions: [],//{desc,options:[{desc,id}],type}
            desc: '',//问卷描述
        }
        this.canvasesWithOptsInfo = []//{canvas,opts}
    }

    componentDidMount() {
        this.componentReLinked()
    }

    componentWillReceiveProps(nextProps) {
        this.componentReLinked()
        // this.renderCharts()
    }

    renderCharts() {
        console.log('renderCharts()')

        this.canvasesWithOptsInfo.map(({canvas, opts}) => {
            const ctx = canvas.getContext('2d');


            // console.log(opts)
            const optCounts = opts.map(opt => {
                return opt.count
            })
            const optDescs = opts.map(opt => {
                return opt.desc
            })

            const data = {
                datasets: [{
                    // data: [10, 20, 30],
                    data: optCounts,
                    backgroundColor: [
                        colors.red,
                        colors.yellow,
                        colors.blue,
                        colors.green,
                    ]
                }],
                // labels: ['A', 'B', 'C', 'D', 'E'],
                labels: optDescs,
            }

            new Chart(ctx, {
                type: 'pie',
                data: data,
                options: {
                    legend: {
                        display: false,
                    },
                    tooltips: {
                        // titleFontSize: 20,
                        bodyFontSize: 20,
                    }
                },
            })
        })

        this.canvasesWithOptsInfo = []
    }

    //Here to render canvases after rendering
    componentDidUpdate() {
        console.log('Did updated')
        this.renderCharts()
    }

    //重新链接到这个页面
    componentReLinked() {
        this.ajaxAndRenderData()
    }

    ajaxAndRenderData() {
        const me = this
        me.getAjaxData()
            .then(me.formatData.bind(me))
            .then(me.setState.bind(me))
    }

    getAjaxData() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: '/api/StatisticInfo',
                data: {id: this.props.match.params.id},
            }).then(response => {
                const res = ajaxUtil.formatAjaxResponse(response)
                if (ajaxUtil.checkIfOk(res)){
                    console.log('Check OK')
                    resolve(res.Data)
                }
                reject('格式化出错')
            }, err => {
                reject('请求统计数据失败')
            })
        })
        // return this.getMockAjaxData()
    }

    getMockAjaxData() {
        return Promise.resolve({
            "Describe": "C++调查",
            "QuestionCollection": [
                {
                    "Describe": "C++难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "不难",
                            "Id": 1,
                            Count: 3,
                        },
                        {
                            "Describe": "难",
                            "Id": 2,
                            Count: 2,
                        }
                    ],
                    "Type": 0
                },
                {
                    "Describe": "Java难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "不难",
                            Count: 9,
                            "Id": 3
                        },
                        {
                            "Describe": "难",
                            Count: 3,
                            "Id": 4
                        }
                    ],
                    "Type": 0
                },
                {
                    "Describe": "计算机组成原理难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "难",
                            Count: 50,
                            "Id": 5
                        },
                        {
                            "Describe": "很难",
                            Count: 5,
                            "Id": 6
                        }
                    ],
                    "Type": 0
                }
            ],
            "Title": "课程满意度调查"
        })
    }

    formatData(oldData) {
        const result = this.simpleMapToState(oldData)
        return Promise.resolve(result)
    }

    simpleMapToState(data) {
        console.log(data)
        const result = {
            desc: data["Describe"],
            title: data["Title"],
        }

        result.questions = data["QuestionCollection"].map(que => {

            const options = que["QuestionOptionCollection"].map(opt => {
                return {desc: opt["Describe"], id: opt["Id"], count: opt["Count"]}
            })

            return {desc: que["Describe"], type: que["Type"], options}
        })

        // console.info('Formatted: ' + JSON.stringify(result))
        return result
    }

    render() {
        const ques = this.state.questions.map(que => {
            const opts = que.options.map((opt, index) => {
                return (<ul>
                    <li>{index + 1}. {opt.desc}</li>
                </ul>)
            })

            const canvasWithOptsInfo = (<canvas ref={canvas => {
                this.canvasesWithOptsInfo.push({
                    canvas,
                    opts: que.options
                })
            }} height='400' width='400'></canvas>)

            return (<Paper zDepth={4} style={myStyles.paper}>
                <h4>{que.desc}</h4>
                <div>{opts}</div>
                <div style={{width: '200px', height: '200px'}}>
                    {canvasWithOptsInfo}
                </div>
            </Paper>)
        })

        return (
            <div style={myStyles.container}>
                <h2>统计页面</h2>
                <p style={{color: 'red'}}>由于架构问题，请不要在此页面点"问卷信息统计"按钮重新链接到该页面</p>
                <h2>{this.state.title || '标题载入中...'}</h2>
                <h4>{this.state.desc || ''}</h4>


                {ques}


            </div>
        )
    }
}
